package com.after.saas.common.exception.handler;

import cn.hutool.core.util.ObjectUtil;
import com.after.saas.common.constants.ErrorCodeEnum;
import com.after.saas.common.constants.Result;
import com.after.saas.common.exception.BaseException;
import com.after.saas.common.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2021/6/10 17:12
 * @Created by hjchen
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BaseException.class)
    public Result<?> baseException(BaseException e) {
        log.error("cause {} message {}", e.getCause(), e.getMessage());
        if (ObjectUtil.isNotEmpty(e.getResultEnum()))
            return ResponseUtil.FAILURE(e.getResultEnum());
        return ResponseUtil.FAILURE(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("cause {} message {}", e.getCause(), e.getMessage());
        e.printStackTrace();
        return ResponseUtil.FAILURE(ErrorCodeEnum.INNER_ERROE);
    }

    @ExceptionHandler(value = {BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})
    public Result<?> handleParameterVerificationException(Exception e) {
        String errMsg = e.getMessage();
        if (e instanceof MethodArgumentNotValidException) {//处理 json 请求体调用接口校验失败抛出的异常
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            errMsg = ex.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("、"));
        } else if (e instanceof BindException) {//处理form data 方式调用接口校验失败抛出的异常
            BindException ex = (BindException) e;
            errMsg = ex.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("、"));
        } else if (e instanceof ValidationException) {//处理单个参数校验失败抛出的异常
            ConstraintViolationException ex = (ConstraintViolationException) e;
            errMsg = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("、"));
        }
        return ResponseUtil.FAILURE(HttpStatus.BAD_REQUEST.value(), errMsg);
    }

}